package com.xilihui.xlh.business.activitys.store;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.activitys.LoginActivity;
import com.xilihui.xlh.business.activitys.StoreDetailsActivity;
import com.xilihui.xlh.business.dialogs.StoreBuyDialog;
import com.xilihui.xlh.business.entities.RecommendGoodEntity;
import com.xilihui.xlh.business.entities.StoreDetailsEntity;
import com.xilihui.xlh.business.requests.StoreRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.glide.ImageHelper;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/9/3.
 */

public class StoreGoodDetailsActivity extends BaseCompatActivity implements OnRefreshListener, OnLoadMoreListener {
    
    
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerView;
    @BindView(R.id.tv_collect)
    TextView tv_collect;

    Banner banner;
    TextView tv_price;
    TextView tv_title;
    TextView tv_yunfei;
    TextView tv_volue;
    TextView tv_jinfeng;
    TextView tv_evaluationNum;
    
    RecyclerView recyclerView_pj;
    RecyclerView recyclerView_tp;
    TextView tv_see_Evaluation;
    
    String goods_id = "";
    int page = 1;
    String collect = "0";
    boolean isLogin = false;
    
    StoreDetailsEntity storeDetailsEntity;
    
    BaseAdapter<StoreDetailsEntity.GoodsInfoBean.GetcommentBean> conmentAdpater;
    BaseAdapter<StoreDetailsEntity.GoodsInfoBean.GoodsContentImagesBean> imageAdapter;
    BaseAdapter<RecommendGoodEntity.GoodsBean> baseAdapter;
    
    ArrayList<StoreDetailsEntity.GoodsInfoBean.GoodsImagesBean> bannerData = new ArrayList<>();
    ArrayList<StoreDetailsEntity.GoodsInfoBean.GetcommentBean> commentData = new ArrayList<>();
    ArrayList<StoreDetailsEntity.GoodsInfoBean.GoodsContentImagesBean> imageData = new ArrayList<>();
    ArrayList<RecommendGoodEntity.GoodsBean> goodsBeans = new ArrayList<>();
    
    @Override
    public int getLayout() {
        return R.layout.activity_store_good_details;
    }

    @Override
    public String initTitle() {
        return "商品详情";
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        
        isLogin = (boolean) SPUtil.get(StoreGoodDetailsActivity.this,SPUtil.IS_LOGIN,false);
        
        
        goods_id = getIntent().getStringExtra("goods_id");
        
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
        
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
        
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.tv_color_fff,R.dimen.divider_space,
                LinearLayout.HORIZONTAL));
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.tv_color_fff,R.dimen.divider_space,
                LinearLayout.VERTICAL));
        recyclerView.setLoadingMoreEnabled(false);
        initHeadView();
        
        baseAdapter = new BaseAdapter<RecommendGoodEntity.GoodsBean>(this,goodsBeans) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_shop_good;
            }

            @Override
            protected void getView(BaseViewHolder holder, RecommendGoodEntity.GoodsBean entity, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.sdv);
                simpleDraweeView.setImageURI(UrlConst.baseUrl() + entity.getOriginal_img());
                                
                holder.setText(R.id.tv_title,entity.getGoods_name());
                holder.setText(R.id.tv_price,"￥"+entity.getShop_price());
                holder.setText(R.id.tv_num,"售出"+entity.getSales_sum()+"件");
                
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(StoreGoodDetailsActivity.this, StoreGoodDetailsActivity.class);
                        intent.putExtra("goods_id",goods_id);
                        startActivity(intent);
                        finish();
                    }
                });
                
            }
        };
        
        
        recyclerView.setAdapter(baseAdapter);
        baseAdapter.setAnimationsLocked(false);
        
        getData(true);
        getGoods(true);
        
        
    }

    @Override
    public void initData() {
        
    }
    
    public void initHeadView(){

        View view = LayoutInflater.from(StoreGoodDetailsActivity.this).inflate(R.layout.rerycler_item_store_good_details_head,null);
        
        banner = (Banner)view.findViewById(R.id.banner);
        tv_price = (TextView)view.findViewById(R.id.tv_price);
        tv_title = (TextView)view.findViewById(R.id.tv_name);
        tv_yunfei = (TextView)view.findViewById(R.id.tv_yunfei);
        tv_volue = (TextView)view.findViewById(R.id.tv_num);
        tv_jinfeng = (TextView)view.findViewById(R.id.tv_jifen);
        tv_evaluationNum = (TextView)view.findViewById(R.id.tv_pingjia); 
        
        recyclerView_pj = (RecyclerView)view.findViewById(R.id.recyclerview_pj);
        recyclerView_tp = (RecyclerView)view.findViewById(R.id.recyclerview_tp);
        
        tv_see_Evaluation = (TextView)view.findViewById(R.id.tv_see_pingjia); 
        
        tv_see_Evaluation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(StoreGoodDetailsActivity.this,EvaluationActivity.class);
                intent.putExtra("goods_id",goods_id);
                startActivity(intent);
            }
        });
        
        recyclerView_pj.setLayoutManager(new LinearLayoutManager(this));
        recyclerView_tp.setLayoutManager(new LinearLayoutManager(this));
        recyclerView_pj.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.view_line,
                R.dimen.divider_line, LinearLayout.VERTICAL));
        
        conmentAdpater = new BaseAdapter<StoreDetailsEntity.GoodsInfoBean.GetcommentBean>(this,commentData) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_store_evaluate;
            }

            @Override
            protected void getView(BaseViewHolder holder, StoreDetailsEntity.GoodsInfoBean.GetcommentBean entity, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.sdv);
                simpleDraweeView.setImageURI(UrlConst.baseUrl() + entity.getUser().getHead_pic());
                
                TextView tv_username = (TextView)holder.getView(R.id.tv_username);
                tv_username.setText(entity.getUser().getNickname());
                String zan_type = entity.getZan_num();
                Drawable drawable = null;
                if(zan_type.equals("0")){
                    drawable = getResources().getDrawable(R.mipmap.ic_eva_bad);
                }else if(zan_type.equals("1")){
                    drawable = getResources().getDrawable(R.mipmap.ic_eva_normal);
                }else if(zan_type.equals("2")){
                    drawable = getResources().getDrawable(R.mipmap.ic_eva_good);
                }
                drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                tv_username.setCompoundDrawables(null,null,drawable,null);
                
                holder.setText(R.id.tv_time,entity.getAdd_time());
                holder.setText(R.id.tv_pingjia,entity.getContent());
            }
        };
        recyclerView_pj.setAdapter(conmentAdpater);
        imageAdapter = new BaseAdapter<StoreDetailsEntity.GoodsInfoBean.GoodsContentImagesBean>(this,imageData) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_store_img;
            }

            @Override
            protected void getView(BaseViewHolder holder, StoreDetailsEntity.GoodsInfoBean.GoodsContentImagesBean entity, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.sdv);
                simpleDraweeView.setImageURI(UrlConst.baseUrl()+entity.getImage_url());
                LogUtil.i("mylog",UrlConst.baseUrl()+entity);
            }
        };
        recyclerView_tp.setAdapter(imageAdapter);
        conmentAdpater.setAnimationsLocked(true);
        imageAdapter.setAnimationsLocked(true);
        
        recyclerView.addHeaderView(view);
        
    }
    
    
    public void getData(boolean isLoading){
        StoreRequest.details(StoreGoodDetailsActivity.this,goods_id)
                .compose(DoTransform.<StoreDetailsEntity>applyScheduler(this,isLoading))
                .compose(this.<StoreDetailsEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<StoreDetailsEntity>(this) {
                    @Override
                    protected void onSuccess(StoreDetailsEntity entity) {
                        
                        storeDetailsEntity = entity;
                        collect = entity.getCollect();
                        handleImage(collect);
                        
                        banner.setImages(entity.getGoods_info().getGoods_images());
                        banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                StoreDetailsEntity.GoodsInfoBean.GoodsImagesBean image = (StoreDetailsEntity.GoodsInfoBean.GoodsImagesBean) path;
                                ImageHelper.display(StoreGoodDetailsActivity.this,imageView,UrlConst.baseUrl()+image.getImage_url());     
                            }
                        });
                        
                        banner.start();
                        
                        tv_price.setText("￥"+entity.getGoods_info().getShop_price());
                        tv_title.setText(entity.getGoods_info().getGoods_name());
                        
                        String yunfei = "";
                        if(entity.getGoods_info().getIs_free_shipping().equals("1")){
                            yunfei = "包邮";
                        }else {
                            yunfei = "不包邮";
                        }
                        tv_yunfei.setText("运费："+yunfei);
                        tv_volue.setText("已销售"+entity.getGoods_info().getSales_sum()+"件");
                        tv_jinfeng.setText("购买可得"+entity.getGoods_info().getGive_integral()+"积分");
                        tv_evaluationNum.setText("宝贝评价("+entity.getGoods_info().getComment_num()+")");
                        
                        commentData.clear();
                        commentData.addAll(entity.getGoods_info().getGetcomment());
                        conmentAdpater.setList(commentData);
                        
                        imageData.clear();
                        imageData.addAll(entity.getGoods_info().getGoods_content_images());
                        imageAdapter.setList(imageData);
                        
                        smartRefreshLayout.finishRefresh();
                        
                    }

                    @Override
                    protected void onFail(String msg) {
                        smartRefreshLayout.finishRefresh();
                    }
                });
    }
        
    public void getGoods(boolean isLoading){
        StoreRequest.recommendGood(page)
                .compose(DoTransform.<RecommendGoodEntity>applyScheduler(this,isLoading))
                .compose(this.<RecommendGoodEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<RecommendGoodEntity>(this) {
                    @Override
                    protected void onSuccess(RecommendGoodEntity entity) {
                        if(page==1){
                            goodsBeans.clear();
                        }
                        
                        goodsBeans.addAll(entity.getGoods());
                        
                        baseAdapter.setList(goodsBeans);
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();
                        
                        if(page>=entity.getPageCount()){
                            smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }else {
                            smartRefreshLayout.setNoMoreData(false);
                        }
                        
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
    }
    

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getData(false);
        getGoods(false);
    }
    
    @OnClick(R.id.tv_collect)
    public void collectCart(){
        isLogin = (boolean) SPUtil.get(StoreGoodDetailsActivity.this,SPUtil.IS_LOGIN,false);
        if(isLogin){
            String type = "";
            if(collect.equals("1")){
                type = "0";
            }else if(collect.equals("0")){
                type = "1";
            }

            final String finalType = type;
            StoreRequest.collectCart(StoreGoodDetailsActivity.this,goods_id,type)
                    .compose(DoTransform.<BaseEntity>applyScheduler(StoreGoodDetailsActivity.this,true))
                    .compose(this.<BaseEntity>bindToLifecycle())
                    .subscribe(new HttpSubscriber<BaseEntity>(this) {
                        @Override
                        protected void onSuccess(BaseEntity entity) {
                            collect = finalType;
                            ToastUtil.toastShortPositive(entity.getMsg());
                            handleImage(collect);
                        }

                        @Override
                        protected void onFail(String msg) {
                            ToastUtil.toastShortNegative(msg);
                        }
                    });
        }else {
            goLogin();
        }
        
    }
    
    @OnClick(R.id.tv_cart)
    public void goCart(){
        isLogin = (boolean) SPUtil.get(StoreGoodDetailsActivity.this,SPUtil.IS_LOGIN,false);
        if(isLogin){
            Intent intent = new Intent(StoreGoodDetailsActivity.this, CartActivity.class);
            startActivity(intent);
            finish(); 
        }else {
            goLogin();
        }
        
    }
    
    @OnClick(R.id.tv_addCart)
    public void addCart(){
        isLogin = (boolean) SPUtil.get(StoreGoodDetailsActivity.this,SPUtil.IS_LOGIN,false);
        if(isLogin){
            StoreBuyDialog addCartDialog = new StoreBuyDialog(this,storeDetailsEntity,goods_id,"",0,1);
            addCartDialog.show();
        }else {
            goLogin();
        }
        
    }
    
    @OnClick(R.id.tv_buy)
    public void buy(){
        isLogin = (boolean) SPUtil.get(StoreGoodDetailsActivity.this,SPUtil.IS_LOGIN,false);
        if(isLogin){
            StoreBuyDialog buyDialog = new StoreBuyDialog(this,storeDetailsEntity,goods_id,"",0,2);
            buyDialog.show();
        }else {
            goLogin();
        }
        
    }

    public void handleImage(String collect){
        if(collect.equals("1")){
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_shop_collected);
            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            tv_collect.setCompoundDrawables(null,drawable,null,null);
        }else {
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_shop_collect);
            drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
            tv_collect.setCompoundDrawables(null,drawable,null,null);
        }
    }
    
    public void goLogin(){
        Intent intent = new Intent(StoreGoodDetailsActivity.this, LoginActivity.class);
        startActivity(intent);
    }
    
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page = page + 1;
        getGoods(false);
    }

    @Override
    public void onEventMainThread(YEventBuses.Event event) {
        super.onEventMainThread(event);
        if(event.is("pay")){
            finish();
        }
    }
    
}
